<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Code Igniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		Gabriel Popa
 * @copyright	Copyright (c) 2008, IELLO-DEV
 * @license		http://www.codeignitor.com/user_guide/license.html
 * @link		http://www.codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

class Myxml {
	
	function Myxml(){
		$this->CI =& get_instance();
		log_message('debug', "XML library initialized");
	}
	
	  public function load($file) {
	  	
		    if (fopen($file,"r")) {
			    $this->document = utf8_encode (file_get_contents($file));
			    $this->filename = $file;
			
			    return true;  
		    } else {
  				return false;
		    }
	
	  }  

	  public function parse () {
	
		    $xml = $this->document;
		    if ($xml == '') {
		      return false;
		    } else {
			    $doc = new DOMDocument ();
			    $doc->preserveWhiteSpace = false;
			    if ($doc->loadXML ($xml)) {
			      $array = $this->flatten_node ($doc);
			      if (count ($array) > 0) {
			        return $array;
			      } else {
			      	return false;
			      }
			    }    	
		    }
			
	  } 

	  private function flatten_node ($node) {
	
		    $array = array();
		
		    foreach ($node->childNodes as $child) {
		      if ($child->hasChildNodes ()) {
		        if ($node->firstChild->nodeName == $node->lastChild->nodeName && $node->childNodes->length > 1) {
		          $array[$child->nodeName][] = $this->flatten_node ($child);
		        }
		        else {
		          $array[$child->nodeName][] = $this->flatten_node($child);
		
		          if ($child->hasAttributes ()) {
		            $index = count($array[$child->nodeName])-1;
		            $attrs =& $array[$child->nodeName][$index]['__attrs'];
		            foreach ($child->attributes as $attribute) {
		              $attrs[$attribute->name] = $attribute->value;
		            }
		          }
		        }
		      }
		      else {
		        return $child->nodeValue;
		      }
		    }
		    return $array;
			
	  } 	
}		
?>
